<?php
/**
 * 上传控制类
 * User: Administrator
 * Date: 2018/11/2 0002
 * Time: 22:07
 */

namespace app\index\controller;
use library\AliOss;
use exception\ResponsableException;
use think\Db;
class Upload extends  CommonController
{
    protected $_require_login = true;
    /**
     * 上传
     */
    public function index()
    {
         try{
             $avator = $this->request->file('avatar');
             $e= AliOss::upload($avator);
             $this->upload_save($e['info']['url']);
             return $this->response->api(['url'=>$e['info']['url']],self::SUCCESS_CODE,'上传成功');
         }catch (\Exception $e){
             return $this->response->api([],self::ERROR_CODE,'上传失败');
         }
    }

    public function upload_index()
    {
        $param = $this->request->param();
        $this->assign('page',$param['page']);
        return $this->fetch('upload/index');
    }

    public function upload_save($url)
    {
       $data =[
           'ui_id'=>$this->uid,
           'url' => $url,
           'status' => 1,
           'created_at'=>date('Y-m-d H:i:s',time())
        ];
       Db::table('user_upload_history')->insert($data);
    }

    public function get_upload_url()
    {
        $res = Db::table('user_upload_history')->where('status',1)->order('created_at')->find();
        return $this->response->api(['url'=>$res['url'],'ui_id'=>$res['ui_id']],self::SUCCESS_CODE,'');
    }

    public function del_upload()
    {
        Db::table('user_upload_history')->where('ui_id',$this->uid)->update(['status'=>2]);
        return $this->response->api([],self::SUCCESS_CODE,'');
    }

}